<template>
  <div class="birth-sms">
    <div class="card">
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
      >
        <el-table-column prop="id" label="ID" align="center" />
        <el-table-column prop="name" label="模版名称" align="center" />
        <el-table-column prop="created_at" label="创建时间" align="center">
          <template v-slot="{ row }">
            {{ dayjs(row.created_at).format('YYYY-MM-DD HH:MM:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="是否启用" align="center">
          <template v-slot="{ row }">
            <el-tag
              v-if="row.birthday_value?.display === 1"
              type="success"
            >
              已启用
            </el-tag>
            <el-tag
              v-else
              type="info"
            >
              未启用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button
              v-if="!row.birthday_value?.display"
              size="mini"
              type="primary"
              @click="handleEnable(row)"
            >
              启 用
            </el-button>

            <el-button size="mini" type="primary" @click="edit(row)">编 辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <WithDialog
      :visible.sync="dialogVisible"
      width="45%"
      title="短信模板编辑"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    >
      <div style="width: 100%;">

        <div v-if="previewContent" class="preview">
          <div class="preview-title">模版原内容：</div>
          <div>
            <pre style="white-space: pre-line; margin: 0;">
              <div style="line-height: 28px;" v-html="previewContent" />
            </pre>
          </div>
        </div>

        <div>修改模版内容：</div>
        <div class="template-content">
          <!-- 使用 v-for 动态渲染文本片段和输入框 -->
          <template v-for="(item, index) in templateParts">
            <template v-if="item.type === 'text'">
              {{ item.content }}
            </template>
            <template v-else>
              <el-input
                v-if="!isStatic(item.placeholder)"
                :key="index"
                v-model="contentArr[item.index]"
                :placeholder="item.placeholder"
                style="width: 130px; margin: 4px;"
                size="small"
              />

              <template v-else>
                [{{ item.placeholder }}]
              </template>
            </template>
          </template>
        </div>
      </div>
    </WithDialog>
  </div>
</template>
<script>
import { getBirthdaySmsTemplate, editBirthdaySmsTemplate } from '@/api/birth'
import WithDialog from '@/components/WithDialog/withDialog.vue'
import { mapGetters } from 'vuex'
import { sleep } from '@/utils'
import dayjs from 'dayjs'
export default {
  name: '',
  components: { WithDialog },
  data() {
    return {
      list: [],
      currentTemplate: null,
      dialogVisible: false,
      contentArr: [],
      placeholderNames: [],
      templateParts: [], // 新增：存储模板解析后的部分
      staticPlaceholders: ['员工姓名'],
      contentMap: {},
      loading: false
    }
  },
  computed: {
    ...mapGetters(['defaultCompany']),
    previewContent() {
      if (!this.currentTemplate?.content) return ''

      let result = this.currentTemplate.content
      this.placeholderNames.forEach((name, index) => {
        result = result.replace(
          new RegExp(`\\$\\{${name}\\}`),
          `<span style="color: #4A9FF9;">[${name}]</span> `
        )
      })
      return result
    },

    defaultContent() {
      return {
        '公司名称': this.defaultCompany?.name
      }
    }

  },
  created() {
    this.getBirthdaySmsTemplate()
  },
  methods: {
    dayjs,
    async getBirthdaySmsTemplate() {
      this.loading = true
      try {
        const res = await getBirthdaySmsTemplate()
        this.list = res.data
        console.log('res --------->', res)
      } catch (error) {
        this.$message.error('信息获取失败')
      } finally {
        await sleep(500)
        this.loading = false
      }
    },

    parseTemplate(templateText) {
      if (!templateText) {
        this.templateParts = []
        return
      }

      const parts = []
      let lastIndex = 0
      const placeholderRegex = /\$\{([^}]+)\}/g
      let match
      let placeholderIndex = 0

      while ((match = placeholderRegex.exec(templateText)) !== null) {
        // 添加占位符前的文本
        if (match.index > lastIndex) {
          parts.push({
            type: 'text',
            content: templateText.substring(lastIndex, match.index)
          })
        }

        // 检查是否是特定的占位符
        if (match[1] === '员工姓名') {
          // 直接将特定占位符替换为 [员工姓名] 并作为文本处理
          parts.push({
            type: 'text',
            content: '[员工姓名]'
          })
        } else {
          // 添加占位符对应的输入框配置
          parts.push({
            type: 'input',
            placeholder: match[1],
            index: placeholderIndex
          })
          placeholderIndex++
        }

        lastIndex = match.index + match[0].length
      }

      // 添加最后一段文本
      if (lastIndex < templateText.length) {
        parts.push({
          type: 'text',
          content: templateText.substring(lastIndex)
        })
      }

      this.templateParts = parts
    },
    generateArray(templateText) {
      const placeholders = templateText.match(/\$\{([^}]+)\}/g) || []

      // 提取占位符名称
      this.placeholderNames = placeholders.map(p =>
        p.match(/\${([^}]+)}/)[1]
      )

      const dynamicPlaceholders = this.placeholderNames.filter(
        name => !this.staticPlaceholders.includes(name)
      )

      if (this.currentTemplate.birthday_value?.content) {
        this.contentArr = JSON.parse(this.currentTemplate.birthday_value?.content)
      } else {
        this.contentArr = dynamicPlaceholders.map(placeholder => this.defaultContent[placeholder] || '')
      }
    },
    edit(row) {
      this.currentTemplate = row
      this.contentArr = {}
      this.placeholderNames = []
      this.generateArray(row.content)
      this.parseTemplate(row.content) // 使用新的解析方法
      this.dialogVisible = true
    },
    handleConfirm() {
      // 在这里处理确认逻辑
      if (this.contentArr.includes('')) {
        return this.$message.error('请将内容填写完整')
      }

      const params = {
        id: this.currentTemplate.id,
        contents: JSON.stringify(this.contentArr)
      }

      this.editBirthdaySmsTemplate(params)
    },

    isStatic(content) {
      return this.staticPlaceholders.includes(content)
    },

    handleCancel() {
      this.dialogVisible = false
    },

    async editBirthdaySmsTemplate(data) {
      try {
        const res = await editBirthdaySmsTemplate(data)
        console.log('res --------->', res)
        this.$message.success('操作成功')
        this.dialogVisible = false
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '操作失败')
      }
    },

    refresh() {
      this.getBirthdaySmsTemplate()
    },

    handleEnable(row) {
      console.log('row --------->', row)
      const params = {
        id: row.id,
        display: 1
      }

      this.editBirthdaySmsTemplate(params)
    }
  }
}
</script>
<style lang="scss" scoped>
.birth-sms {
  padding: 20px;

  .template-content {
    line-height: 32px;
    margin: 10px 0;
  }

  .preview {
    margin-bottom: 20px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 4px;

    &-title {
      font-weight: bold;
    }
  }
}
</style>
